package com.longrise.android.byjk.plugins.tabfirst.answerQuestion;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.tabfirst.commentdialog.ComDialog;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.DeviceUtils;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.widget.view.BaseFrameView;


/**
 * Created by sujizhong on 16/10/18.
 * 问答详情
 */
public class AnswerDetailActivity extends BaseActivity implements BaseFrameView.ReloadListener {

    private static final String TAG = "AnswerDetailActivity";

    public static final String EXTRA_ANSWER_URL = "EXTRA_ANSWER_URL";

    private final int REQUEST_CODE = 11;

    private final String ON_BUNDLE_SAVE = "ON_BUNDLE_SAVE";

    private final int MSG_PAGE_START = 0;
    private final int MSG_PAGE_ERROR = 1;
    private final int MSG_PAGE_FINISH = 2;
    private final int MSG_SHOW_CONTENT_BOX = 3;
    private final int MSG_SHOW_TOAST = 4;

    private Toolbar mTitle;
    private TextView mBtnTW;

    public WebView mWebView;
    private WebSettings mWebSettings;
    private BaseFrameView mBaseFrameView;

    private boolean mLoadIsError = false;
    private boolean mDestory;

    private String mAnswerUrl = "";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mDestory) return;
            int what = msg.what;
            switch (what) {
                case MSG_PAGE_START:
                    mWebView.setVisibility(View.GONE);
                    mBaseFrameView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    break;

                case MSG_PAGE_ERROR:
                    mWebView.setVisibility(View.GONE);
                    mBaseFrameView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    break;

                case MSG_PAGE_FINISH:
                    mBaseFrameView.setVisibility(View.GONE);
                    mWebView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    mBtnTW.setVisibility(mWebView.canGoBack() ? View.GONE : View.VISIBLE);
                    break;

                case MSG_SHOW_CONTENT_BOX:
                    openComDialog();
                    break;

                case MSG_SHOW_TOAST:
                    String hint = (String) msg.obj;
                    DZZWTools.showToast(AnswerDetailActivity.this, hint, Toast.LENGTH_SHORT);
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mAnswerUrl = savedInstanceState.getString(ON_BUNDLE_SAVE, "");
        }
        return R.layout.activity_answerdetail;
    }


    @Override
    public void initView() {
        getExtraData();
        init();
        initTitle();

    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.answerdetailactivity_wd));
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onKeyDown(KeyEvent.KEYCODE_BACK, null);
            }
        });
    }

    private void getExtraData() {
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra(EXTRA_ANSWER_URL)) {
            String url = intent.getStringExtra(EXTRA_ANSWER_URL);
            StringBuilder urlBuilder = new StringBuilder(url);
            urlBuilder.append("&cardno=" + UserInfor.getInstance().getUsersfzh());
            urlBuilder.append("&userid=" + UserInfor.getInstance().getUserid());
            mAnswerUrl = urlBuilder.toString();
        }
    }

    public void init() {
        mBtnTW = (TextView) findViewById(R.id.answerdetailacitivity_bt);
        regEvent();
        initWebView();

        if (checkNetwork()) {
            mHandler.sendEmptyMessage(MSG_PAGE_START);
            load(mAnswerUrl);
        }
    }

    private void initWebView() {
        mBaseFrameView = (BaseFrameView) findViewById(R.id.answerdetailactivity_baseframeview);
        mBaseFrameView.setOnReloadListener(this);
        mWebView = (WebView) findViewById(R.id.answerdetailactivity_webview);
        setWebSetting();
    }

    private void regEvent() {
        if (mBtnTW != null) {
            mBtnTW.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_BUTTON_PRESS:
                            ScaleAnimation animation = new ScaleAnimation(1f, 0.8f, 1f, 0.8f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                            animation.setDuration(200);
                            animation.setFillAfter(true);
                            mBtnTW.startAnimation(animation);
                            break;

                        case MotionEvent.ACTION_UP:
                        case MotionEvent.ACTION_CANCEL:
                            ScaleAnimation animation1 = new ScaleAnimation(0.8f, 1f, 0.8f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                            animation1.setDuration(200);
                            animation1.setFillAfter(true);
                            mBtnTW.startAnimation(animation1);
                            animation1.setAnimationListener(new Animation.AnimationListener() {
                                @Override
                                public void onAnimationStart(Animation animation) {
                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {
                                    openAnswerActivity();
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {
                                }
                            });
                            break;
                    }
                    return true;
                }
            });
        }
    }

    private void setWebSetting() {
        mWebSettings = mWebView.getSettings();

        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.addJavascriptInterface(new NewsJSCallback(), "bb");
    }

    private void load(String url) {
        PrintLog.e(TAG, "url: " + url);
        mWebView.loadUrl(url);
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
                mLoadIsError = true;
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
            }
        }
    };

    private void openAnswerActivity() {
        Intent intent = new Intent(this, AnswerActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AnswerActivity.RESULT_CODE && data != null) {
            String content = data.getStringExtra("answeractivity_content");
            if (!TextUtils.isEmpty(content)) {
                mWebView.loadUrl("javascript:$_$.addAnswer('" + content + "')");
            }
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (checkNetwork()) {
                mHandler.sendEmptyMessage(MSG_PAGE_START);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mLoadIsError) {
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            } else {
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadIsError = true;
        }
    };

    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            mLoadIsError = false;
            load(mAnswerUrl);
        }
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private class NewsJSCallback {

        public NewsJSCallback() {
        }

        @JavascriptInterface
        public void loadFinish() {
            Message message = mHandler.obtainMessage();
            if (mLoadIsError) {
                message.what = MSG_PAGE_ERROR;
            } else {
                message.what = MSG_PAGE_FINISH;
            }
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void shareParams(String title, String sharepath, String sharecontent) {
        }

        @JavascriptInterface
        public void setTitle(final String title) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mTitle != null) {
                        mTitle.setTitle(title);
                    }
                }
            });
        }

        @JavascriptInterface
        public void showHintMsg(String msg) {
            if (!TextUtils.isEmpty(msg)) {
                Message message = new Message();
                message.obj = msg;
                message.what = MSG_SHOW_TOAST;
                mHandler.sendMessage(message);
            }
        }

        @JavascriptInterface
        public void pageBack(boolean isback) {
        }

        @JavascriptInterface
        public void showCommentBox() {
            mHandler.sendEmptyMessage(MSG_SHOW_CONTENT_BOX);
        }

        @JavascriptInterface
        public void getDeviceInfor() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:setDeviceInfoForGA('" + DeviceUtils.getVersionName() + "')");
                }
            });
        }

        //xkj infostate: 1:成功  .. 0:完成失败(失败后由网页调用showHintMsg方法去显示提示),
        @JavascriptInterface
        public void aboutIntegral(String infostate, String acquiredscore, String remindwords) {
            if ("1".equals(infostate)) {
//                MyIntegralDialogUtil.showIntegralDailog(AnswerDetailActivity.this, acquiredscore, remindwords);
            }
        }

    }

    private void openComDialog() {
        ComDialog comDialog = new ComDialog(this, new ComDialog.MsgCallback() {
            @Override
            public void msg(String msg) {
                //调用js方法
                if (!TextUtils.isEmpty(msg))
                    mWebView.loadUrl("javascript:$_$.commitAnswer('" + msg + "')");
            }
        });
        comDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        if (event == null) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(EXTRA_ANSWER_URL, mAnswerUrl);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        }
    }

    private void release() {
        mDestory = true;
        if (mWebView != null) {
            mWebView.clearHistory();
            mWebView.destroy();
        }
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }
}
